package cn.onecloud.examples;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * @author Keijack
 *
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService service;

    @RequestMapping("/list.do")
    public ModelAndView listStudent(@RequestParam(required = false, defaultValue = "") String name) {

	QueryStudentParam params = new QueryStudentParam();
	params.setNameLike(name);
	List<Student> students = this.service.list(params);

	ModelMap map = new ModelMap();
	map.put("students", students);

	return new ModelAndView("student/list", map);
    }

    @RequestMapping("/list2.do")
    public String listStudent2(String name, ModelMap map) {
	QueryStudentParam params = new QueryStudentParam();
	params.setNameLike(name);
	List<Student> students = this.service.list(params);

	map.put("students", students);

	return "student/list";
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.GET)
    public ModelAndView addStudent(@ModelAttribute("addForm") AddStudentForm form) {
	return new ModelAndView("student/add");
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    public ModelAndView addStudent(@ModelAttribute("addForm") @Valid AddStudentForm form, BindingResult result) {
	if (result.hasErrors())
	    return new ModelAndView("student/add");

	this.service.add(form.getName());

	return new ModelAndView(new RedirectView("/student/list.do", true));
    }
}
